import {
  shopList
} from '../../static/shop.js'
import {
  users
} from '../../tools/users';
import {
  ds
} from '../../tools/data'
import {
  dsx
} from '../../tools/datax'
import {
  ui
} from '../../tools/ui';
import {
  checkTool
} from '../../tools/check';
import {
  msg
} from '../../tools/msg';
import {
  shops
} from '../../tools/shops';

Page({
  data: {
    maxDis: 5000, // 5公里范围内
    shops: shopList,
    loc: [],
    errMsg: "",
    canSave: false,
    _id: '',
    values: {
      locText: '',
      locHome: '',
      stepFee: 0,
      shop: 0
    },
    pullingDown: false,
  },
  init() {
    const that = this
    ds.cloudGetByOpenid('delivery_addr', res => {
      const addr = res.result?.data[0]
      if (!addr) return ui.loading(false)
      that.addr = addr
      that.updateAddrShow(addr)
    })
  },
  updateAddrShow(addr) {
    this.setData({
      _id: addr._id,
      values: {
        ...addr,
      },
      shopDesc: shops.getShop(addr.shop)?.name || '',
      errMsg: '',
      pullingDown: false,
    })
  },
  // 选择地址
  selLocClick() {
    wx.navigateTo({
      url: '/pages/map/index',
    });
  },
  selAddrCallback(list, index) {
    this.updateAddrShow(list[index])
  },
  onPullDownRefresh() {
    this.setData({
      pullingDown: true
    })
    this.init()
  },
  manageAddrTap() {
    wx.navigateTo({
      url: './manage',
    })
  },
  save2ListTap() {
    const {
      pullingDown,
      values
    } = this.data
    if (pullingDown || !this.check()) return

    ui.loading()
    dsx.cloudGetByOpenid('delivery_addr')
      .then(res => {
        const addr = res.result?.data[0] || {}
        const list = addr?.list || []
        const data2save = {
          ...values,
          distance: values.distance ? values.distance * 1 : undefined
        }
        dsx.cloudUpdate('delivery_addr', addr._id, {
          ...data2save,
          list: [data2save].concat(list),
        }).then(res => {
          this.notifyDeliveryMen()
          ui.loading(false)
          ui.toast(res.result.errMsg.endsWith(':ok'))
        })
      })
  },
  check() {
    const {
      values
    } = this.data
    const fields = [{
      value: values.locText,
      title: '送水地址'
    }, {
      value: values.locHome,
      title: '详细地址'
    }, {
      value: values.name,
      title: '联系人'
    }, {
      value: values.mobile,
      title: '联系电话',
      fn: mobile => checkTool.test(mobile, checkTool.CommonRegex.mobile) ||
        checkTool.test(mobile, checkTool.CommonRegex.telephone)
    }, {
      value: values.shop,
      fn: shop => shop,
      title: '配送门店'
    }, {
      value: values.distance,
      allEmpty: false,
      regex: checkTool.CommonRegex.decimal,
      title: '配送距离'
    }, {
      value: values.stepFee,
      fn: stepFee => stepFee != undefined,
      title: '步梯选项'
    }]
    return checkTool.check(fields)
  },
  notifyDeliveryMen() {
    ds.coll('orders').orderBy('createTime', 'desc')
      .where({
        status: '待配送'
      })
      .limit(1)
      .get()
      .then(res => {
        // console.log(res)
        const order = res.data[0]
        if (!order) return
        msg.notifyDelivery(order._id)
      })
  },
  getPhoneNumber(event) {
    const that = this
    users.getMobile(event, mobile => {
      that.setData({
        values: {
          ...that.data.values,
          mobile: mobile
        }
      })
    })
  },
  // 选中地址回调
  locSelected(res, qqmap) {
    const that = this;
    const {
      values
    } = this.data
    that.setData({
      errMsg: ''
    })

    // const lngLatAddr = ("经度：" + res.longitude + ", 维度：" + res.latitude)
    values.locText = res.name
    values.locHome = res.address
    let loc = [res.longitude, res.latitude];
    this.setData({
      values,
      loc: loc
    });

    let toLocs = [];
    for (let shop of shopList) {
      toLocs.push({
        longitude: shop.loc[0],
        latitude: shop.loc[1]
      });
    }
    let param = {
      mode: "driving",
      from: {
        longitude: loc[0],
        latitude: loc[1]
      },
      to: toLocs,
      success: function (res) { //成功后的回调
        // console.log(res);
        if (res.status != 0) {
          that.setData({
            errMsg: "计算距离错误，代码" + res.status
          });
          return;
        }

        var res = res.result;
        var dis = [];
        var min = -1,
          minShop = 0;
        for (var i = 0; i < res.elements.length; i++) {
          const d = res.elements[i].distance;
          dis.push(d); //将返回数据存入dis数组，
          shopList[i].distance = d / 1000
          if (d < 0 || d < min) {
            min = d;
            minShop = i;
          }
        }

        values.distance = (min / 1000).toFixed(2)
        values.shop = shopList[minShop].id
        that.setData({
          values,
          shopDesc: shopList[minShop].name
        })
        // console.log("min: " + min)
        if (min > that.data.maxDis) {
          that.setData({
            errMsg: ""
          });
          return;
        }
      },
      fail: function (error) {
        console.error(error)
      },
      complete: function (res) {
        // console.log(res)
      }
    };

    qqmap.calculateDistance(param);

  },
  onShow() {
    this.getTabBar().init(1)
  },
  onValueChange(e) {
    this.data.values[e.target.dataset.name] = e.detail.value
    this.setData({
      values: this.data.values
    })
  },
  selShop() {
    const sheets = {}
    shopList.forEach(ele => {
      sheets[ele.id] = ele.name + "：" + ele.desc
    })
    // console.log(sheets, shopList)
    ui.actionSheet(sheets, (desc, key) => {
      const {
        values
      } = this.data
      values.shop = key
      values.distance = (shopList.find(ele => ele.id == key).distance)?.toFixed(2)
      this.setData({
        values,
        shopDesc: shops.getShop(key).name
      })
    })
  },
  selStepFee() {
    const sheets = {
      0: '有电梯或步梯一到二楼',
      1: '步梯三楼',
      2: '步梯四到五楼',
      3: '步梯六到八楼'
    }
    ui.actionSheet(sheets, (desc, key) => {
      const {
        values
      } = this.data
      values.stepFee = +key
      this.setData({
        values
      })
    })
  },
  onLoad() {
    this.init();
  },
});